//
//  VWPlayerSwipeControlLayer.swift
//  VideoPlayer_Example
//
//  Created by JY_NEW on 2021/10/15.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import ijkPlayerManager
import UIKit
import UICreate

/// 滑动控制
class VWPlayerSwipeControlLayer: VWPlayerBaseLayer {
    /// 行为
    enum Action {
        /// 跳转进度
        case seek
        /// 调节音量
        case volume
        /// 调节亮度
        case brightness
    }
    
    override var category: VideoPlayerLayerCategory {
        return .control
    }
    /// 将层级提高，同层级只会显示一个，这个可以和其他控制器共存
    override var level: VideoPlayerLayerLevel {
        return VideoPlayerLayerLevel.control.higher
    }
    override var isDeactiveForTapBlank: Bool {
        return false
    }
    var action: Action = .seek
    /// 开始时间
    var seekStartTime: TimeInterval = 0
    /// 开始声音
    var volumeStartValue: Float = 0
    /// 开始亮度
    var brightnessStartValue: Float = 0
    
    override func loadManager(_ manager: VideoPlayerLayerManagerType) {
        manager.observer.drag.addTarget(self, action: #selector(self.onDrag(_:)))
    }
    override func unloadManager(_ manager: VideoPlayerLayerManagerType) {
        manager.observer.drag.removeTarget(self)
    }
    override func loadContainerView(_ containerView: UIView) {
        containerView.add(self.timeView, layout: .center)
        containerView.add(self.lightView, layout: .top(30), .centerX)
        containerView.add(self.volumeView, layout: .top(30), .centerX)
    }
    
    @objc func onDrag(_ info: VideoPlayerLayerDragInfo) {
        if !self.isAllowControl { return }
        switch info.state {
        case .began:
            switch info.direction {
            case .left, .right:
                self.action = .seek
                self.seekStartTime = self.playerManager?.currentTime ?? 0
            case .down, .up:
                if info.location.x > (self.playerManager?.view.bounds.size.width ?? 0) / 2 {
                    self.action = .volume
                    self.volumeStartValue = self.playerManager?.volume ?? 0
                }else{
                    self.action = .brightness
                    self.brightnessStartValue = self.playerManager?.brightness ?? 0.5
                }
            default: break
            }
            self.active()
        case .ended, .cancelled, .failed:
            self.deactive()
        default: break
        }
        switch self.action {
        case .seek:
            let isBackward = info.currentDirection == .left
            self.timeImageView.isHighlighted = isBackward
            let maxSize = TimeInterval(self.containerView!.bounds.size.width)
            /// 拉满一屏3分钟
            let unit =  3 * 60 / maxSize
            let time = min(max(0, self.seekStartTime + info.currentOffset * unit * (isBackward ? -1 : 1)), self.playerManager?.duration ?? 0)
            self.timeLabel.text = self.timeString(time)
            if info.state == .ended {
                self.playerManager?.seek(to: time, completion: nil)
            }
        case .volume:
            let isDown = info.currentDirection == .down
            ///1点偏移0.01
            let value = min(1, max(0, self.volumeStartValue + Float(info.currentOffset) * 0.01 * (isDown ? -1 : 1)))
            self.volumeProgressView.progress = value
            self.playerManager?.volume = value
        case .brightness:
            let isDown = info.currentDirection == .down
            ///1点偏移0.01
            let value = min(1, max(0, self.brightnessStartValue + Float(info.currentOffset) * 0.01 * (isDown ? -1 : 1)))
            self.lightProgressView.progress = value
            self.playerManager?.brightness = value
        }
    }
    
    override func show(completion: @escaping () -> Void) {
        let view: UIView
        switch self.action {
        case .seek: view = self.timeView
        case .volume: view = self.volumeView
        case .brightness: view = self.lightView
        }
        view.isHidden = false
        self.aniamteShow(for: view, completion: completion)
    }
    override func hide(completion: @escaping () -> Void) {
        let view: UIView
        switch self.action {
        case .seek: view = self.timeView
        case .volume: view = self.volumeView
        case .brightness: view = self.lightView
        }
        self.aniamteHide(for: view) { [weak view] in
            view?.isHidden = true
            completion()
        }
    }
    
    // MARK: 界面控件
    
    lazy var timeView: UIView = {
        let view = UIView(.hidden())
        view.add {
            self.timeImageView.layout(.top, .marginX)
            self.timeLabel.layout(.bottomTop(12))
                .layout(for: .parent, .centerX, .bottom)
        }
        return view
    }()
    
    lazy var timeImageView = UIImageView(.image("vw_player_fast"), .highlighted(image: "vw_player_forward"))
    lazy var timeLabel = UILabel(.font(.pingfang(bold: 12)), .color(.white))
    
    lazy var lightView: UIView = {
        let view = UIView(.hidden(), .bg(.init(white: 0, alpha: 0.32)), .corner(8.25), .size(125, 17))
        view.add {
            UIImageView(.image(.init(named: "vw_player_light_swipe"))).layout(.left(6), .centerY)
            self.lightProgressView.layout(.rightLeft(5))
                .layout(for: .parent, .centerY, .right(5))
        }
        return view
    }()
    
    lazy var lightProgressView: UIProgressView = {
        let progress = UIProgressView(.height(5), .corner(2.5))
        progress.progressTintColor = .systemBlue
        progress.trackTintColor = .white
        return progress
    }()
    
    lazy var volumeView: UIView = {
        let view = UIView(.hidden(), .bg(.init(white: 0, alpha: 0.32)), .corner(8.25), .size(125, 17))
        view.add {
            UIImageView(.image(.init(named: "vw_player_voice_swipe"))).layout(.left(6), .centerY)
            self.volumeProgressView.layout(.rightLeft(5))
                .layout(for: .parent, .centerY, .right(5))
        }
        return view
    }()
    
    lazy var volumeProgressView: UIProgressView = {
        let progress = UIProgressView(.height(5), .corner(2.5))
        progress.progressTintColor = .systemBlue
        progress.trackTintColor = .white
        return progress
    }()
}
